//
//  ARSendGiftController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/20.
//

import UIKit
import SnapKit

/// 发送礼物
class ARSendGiftController: ARBaseModalAlertController {

    private let boatGift = ARGiftModel.boat()
    private let waterGunGift = ARGiftModel.waterGun()
    private let swimmingRingGift = ARGiftModel.swimmingRing()
    
    /// 给某个人购买
    private let userId: String
    
    init(purchseFor userId: String) {
        self.userId = userId
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        updateBalance()
    }

    private func setupUI() {
        let bgView = UIImageView(image: .init(named: "gift_send_bg"))
        
        self.baseContainerView.addSubview(bgView)
        self.baseContainerView.backgroundColor = .clear
        bgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        /// 点击的button
        let boatBtn = UIButton(type: .custom)
        boatBtn.addTarget(self, action: #selector(boatGiftClicked(_:)), for: .touchUpInside)
        let waterGunBtn = UIButton(type: .custom)
        waterGunBtn.addTarget(self, action: #selector(waterGunGiftClicked(_:)), for: .touchUpInside)
        let swimmingRingBtn = UIButton(type: .custom)
        swimmingRingBtn.addTarget(self, action: #selector(swimmingRingGiftClicked(_:)), for: .touchUpInside)
        self.baseContainerView.addSubview(boatBtn)
        self.baseContainerView.addSubview(waterGunBtn)
        self.baseContainerView.addSubview(swimmingRingBtn)
        
        boatBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(24)
            make.top.equalToSuperview().offset(96)
            make.width.height.equalTo(66)
        }
        
        waterGunBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(90)
            make.top.equalToSuperview().offset(29)
            make.width.height.equalTo(88)
        }
        
        swimmingRingBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-33)
            make.top.equalToSuperview().offset(18)
            make.width.height.equalTo(70)
        }
        
        /// 金币
        let boatPriceView = __ARGiftPriceView()
        boatPriceView.coinLabel.text = "\(boatGift.coins)"
        let waterGunPriceView = __ARGiftPriceView()
        waterGunPriceView.coinLabel.text = "\(waterGunGift.coins)"
        let swimmingRingPriceView = __ARGiftPriceView()
        swimmingRingPriceView.coinLabel.text = "\(swimmingRingGift.coins)"
        
        self.baseContainerView.addSubview(boatPriceView)
        self.baseContainerView.addSubview(waterGunPriceView)
        self.baseContainerView.addSubview(swimmingRingPriceView)
        
        boatPriceView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(58)
            make.top.equalToSuperview().offset(168)
        }
        
        waterGunPriceView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(131)
            make.top.equalToSuperview().offset(118)
        }
        
        swimmingRingPriceView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(205)
            make.top.equalToSuperview().offset(101)
        }
        
        self.view.addSubview(balanceView)
        balanceView.snp.makeConstraints { make in
            make.bottom.equalTo(self.baseContainerView.snp.top).offset(2)
            make.centerX.equalTo(self.baseContainerView.snp.right).offset(-75)
        }
    }
    
    @objc private func boatGiftClicked(_ sender: UIButton) {
        purchaseGift(boatGift)
    }
    
    @objc private func waterGunGiftClicked(_ sender: UIButton) {
        purchaseGift(waterGunGift)
    }
    
    @objc private func swimmingRingGiftClicked(_ sender: UIButton) {
        purchaseGift(swimmingRingGift)
    }
    
    @objc private func balanceViewClicked(_ sender: UIButton) {
        let vc = ARBalanceRechargeController()
        let nav = ARNavigationController(rootViewController: vc)
        self.present(nav, animated: true)
    }
    
    /// 购买
    private func purchaseGift(_ giftModel: ARGiftModel) {
        // 判断价格
        if ARUserManager.shared.userModel?.availableCoins ?? 0 < giftModel.coins {
            self.balanceViewClicked(self.balanceView)
            return
        }
        
        func _purchaseSuccess() {
            // 先添加
            switch giftModel.id {
            case ARGiftModel.boatGiftId:
                ARDataCenter.default.sendBoatGiftTo(userId)
            case ARGiftModel.swimmingRingGiftId:
                ARDataCenter.default.sendSwimmingRingGiftTo(userId)
            case ARGiftModel.waterGunGiftId:
                ARDataCenter.default.sendWaterGunGiftTo(userId)
            default: break
            }
            
            showAnimation(giftModel)
        }
        
        // 购买
        self.ar.showLoading()
        ARGiftPurchaseRequest().purchageGift(giftModel.coins) { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            _purchaseSuccess()
        }
    }
    
    private func showAnimation(_ gift: ARGiftModel) {
        self.autoDismiss = false
        self.baseContainerView.isHidden = true
        self.balanceView.isHidden = true
        let view = UIImageView()
        view.ar.setImage(gift.animate)
        view.alpha = 0.0
        self.view.addSubview(view)
        view.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        UIView.animate(withDuration: 0.3) {
            view.alpha = 1.0
        } completion: { flag in
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
                UIView.animate(withDuration: 0.3) {
                    view.alpha = 0.0
                } completion: { flag in
                    self.dismiss(animated: false)
                }
            }
        }

    }
    
    private func updateBalance() {
        balanceView.coinLabel.text = "\(ARUserManager.shared.userModel?.availableCoins ?? 0)"
    }
    
    private lazy var balanceView: __ARBalanceView = {
        let view = __ARBalanceView(type: .custom)
        view.addTarget(self, action: #selector(balanceViewClicked(_:)), for: .touchUpInside)
        return view
    }()
    
}

fileprivate class __ARGiftPriceView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(coinLabel)
        self.addSubview(coinIconView)
        
        coinIconView.snp.makeConstraints { make in
            make.top.bottom.left.equalToSuperview()
            make.width.equalTo(14)
            make.height.equalTo(12)
        }
        
        coinLabel.snp.makeConstraints { make in
            make.right.centerY.equalToSuperview()
            make.left.equalTo(coinIconView.snp.right).offset(5)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var coinIconView: UIImageView = {
        let view = UIImageView(image: .init(named: "common_coin_icon"))
        return view
    }()
    
    lazy var coinLabel: UILabel = {
        let label = UILabel()
        label.font = ARHelper.font(14, weight: .regular)
        label.textColor = .init(hexString: "#404040")
        return label
    }()
    
}

fileprivate class __ARBalanceView: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.backgroundColor = .init(hexString: "#454545")
        self.layer.cornerRadius = 14
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor(hexString: "#39BAE8")!.cgColor
        
        self.addSubview(coinLabel)
        self.addSubview(coinIconView)
        self.addSubview(arrowView)
        
        coinIconView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(6)
            make.top.equalToSuperview().offset(4)
            make.bottom.equalToSuperview().offset(-4)
            make.width.equalTo(23)
            make.height.equalTo(20)
        }
        
        coinLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(coinIconView.snp.right).offset(6)
        }
        
        arrowView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(coinLabel.snp.right).offset(6)
            make.right.equalToSuperview().offset(-8)
            make.width.equalTo(16)
            make.height.equalTo(16)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var coinIconView: UIImageView = {
        let view = UIImageView(image: .init(named: "common_coin_icon"))
        return view
    }()
    
    private lazy var arrowView: UIImageView = {
        let view = UIImageView(image: .init(named: "common_rightArrow_white"))
        return view
    }()
    
    lazy var coinLabel: UILabel = {
        let label = UILabel()
        label.font = ARHelper.font(16, weight: .regular)
        label.textColor = .white
        return label
    }()
    
}
